var httpToken, commCode, commName, ownerCode;

function getUrlParam(name) {
    return getUrlParamByLocation(window.location.search, name);
}

function getUrlParamByLocation(location, name) {
    console.log(location);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = location.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

/**
 * 从路径中获取到token权限参数，此接口要在路由的首页面手动调用
 * @param success
 * @param failed
 */
function initToken(success, failed) {
    httpToken = getUrlParam("token");
    commCode = getUrlParam("commCode");
    commName = getUrlParam("commName");
    ownerCode = getUrlParam("ownerCode");
    if (httpToken && commCode) {
        if (success)
            success();
    } else {
        if (failed)
            failed();
    }
}


/* 所有的移动端数据请求都必须从这里的封装接口进入 */
function postJson(url, param, success, failed) {
    ajaxJson("post", url, param, success, failed, true);
}


function ajaxJson(type, url, param, success, failed, auth, params) {

    var ajaxData = {
        type: type,
        url: url,
        data: param,
        dataType: "json",
        success: function (data) {
            if (data.ret_code > 0) {
                if (success) {
                    if (data.data) {
                        success(data.data);
                    } else {
                        success(data);
                    }
                }
            } else {
                /* auth 参数避免死循环 */
                if (auth == true && data.status == 302) {
                    if (!httpToken || !commCode) {
                        if (failed)
                            failed();
                        window.location.href = window.location = "/pages/mobile/error/401.html";
                        return;
                    }
                    /* 鉴权 */
                    ajaxJson("post", "/api/auth/registerSessionWithToken?appToken=" + httpToken + "&commCode=" + commCode, null, function () {
                        /* 成功后重复调用接口 */
                        ajaxJson("post", url, param, success, failed, false);
                    }, function () {
                        //window.location.href = window.location = "/pages/mobile/error/401.html";
                        console.log("401");
                        return;
                    }, false);
                    return;
                }
                else if (failed) {
                    failed(data);
                } else {
                    console.log('操作失败！');
                }
            }
        },
        error: function (data, status) {

        }
    }

    if (params) {
        for (var key in params) {
            ajaxData[key] = params[key];
        }
    }

    ajax(ajaxData);
}

function ajax(options) {
    function empty() {
    }

    function obj2Url(obj) {
        if (obj && obj instanceof Object) {
            var arr = [];
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {
                    if (typeof obj[i] == 'function') obj[i] = obj[i]();
                    if (obj[i] == null) obj[i] = '';
                    arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]));
                }
            }
            return arr.join('&').replace(/%20/g, '+');
        } else {
            return obj;
        }
    };
    var opt = {
        url: '', //请求地址
        sync: true, //true，异步 | false　同步，会锁死浏览器，并且open方法会报浏览器警告
        method: 'POST', //提交方法
        data: null, //提交数据
        username: null, //账号
        password: null, //密码
        dataType: 'json', //返回数据类型
        success: empty, //成功返回回调
        error: empty, //错误信息回调
        timeout: 0, //请求超时ms
    };
    for (var i in options) if (options.hasOwnProperty(i)) opt[i] = options[i];

    var accepts = {
        script: 'text/javascript, application/javascript, application/x-javascript',
        json: 'application/json',
        xml: 'application/xml, text/xml',
        html: 'text/html',
        text: 'text/plain'
    };
    var abortTimeout = null;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            xhr.onreadystatechange = empty;
            clearTimeout(abortTimeout);
            var result, dataType, error = false;
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
                if (xhr.responseType == 'arraybuffer' || xhr.responseType == 'blob') {
                    result = xhr.response;
                } else {
                    result = xhr.responseText;
                    dataType = opt.dataType ? opt.dataType : xhr.getResponseHeader('content-type').split(';', 1)[0];
                    for (var i in accepts) {
                        if (accepts.hasOwnProperty(i) && accepts[i].indexOf(dataType) > -1) dataType = i;
                    }
                    try {
                        if (dataType == 'script') {
                            eval(result);
                        } else if (dataType == 'xml') {
                            result = xhr.responseXML
                        } else if (dataType == 'json') {
                            result = result.trim() == '' ? null : JSON.parse(result)
                        }
                    } catch (e) {
                        opt.error(e, xhr.status);
                        xhr.abort();
                    }
                }
                opt.success(result, xhr);
            } else {
                opt.error(xhr.statusText, xhr.status);
            }
        }
    };
    if (opt.method == 'GET') {
        var parse = opt.url.parseURL();
        opt.data = Object.assign({}, opt.data, parse.params);
        opt.url = parse.pathname + '?' + obj2Url(opt.data);
        opt.data = null;
    }
    xhr.open(opt.method, opt.url, opt.sync, opt.username, opt.password);
    if (opt.method == 'POST') xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    if (opt.timeout > 0) {
        abortTimeout = setTimeout(function () {
            xhr.onreadystatechange = empty
            xhr.abort();
            opt.error('timeout', xhr.status);
        }, opt.timeout)
    }

    if (opt.dataType == 'json')
        xhr.setRequestHeader('Accept', 'application/json');
    if (opt.contentType != null && opt.contentType != undefined)
        xhr.setRequestHeader('Content-type', opt.contentType + "; charset=UTF-8");
    xhr.send(opt.data ? obj2Url(opt.data) : null);
}

String.prototype.parseURL = function () {
    'use strict';
    //url解析
    var url = this.toString()
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol,
        origin: a.origin,
        hostname: a.hostname,
        port: a.port,
        search: a.search,
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        pathname: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/'),
        params: (function () {
            var ret = {};
            var seg = a.search.replace(/^\?/, '').split('&').filter(function (v, i) {
                if (v !== '' && v.indexOf('=')) {
                    return true;
                }
            });
            for (var i = 0, element; element = seg[i++];) {
                var idx = element.indexOf('=');
                var key = element.substring(0, idx);
                var val = element.substring(idx + 1);
                ret[key] = val;
            }
            return ret
        })()
    }
};

function nativeCall(cmd, params) {
    window.location.href = "native:" + cmd + ":" + params;
}